package io.renren.modules.humanResources.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import io.renren.common.page.PageData;
import io.renren.common.service.impl.CrudServiceImpl;
import io.renren.common.utils.ConvertUtils;
import io.renren.modules.humanResources.dao.InboundDao;
import io.renren.modules.humanResources.dto.InboundDTO;
import io.renren.modules.humanResources.dto.InventoryDTO;
import io.renren.modules.humanResources.dto.ProductDTO;
import io.renren.modules.humanResources.entity.InboundEntity;
import io.renren.modules.humanResources.entity.InventoryEntity;
import io.renren.modules.humanResources.service.InboundService;
import io.renren.modules.humanResources.service.InventoryService;
import io.renren.modules.humanResources.service.ProductService;
import io.renren.modules.security.user.SecurityUser;
import io.renren.modules.security.user.UserDetail;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 入库信息表
 *
 * @author Mark sunlightcs@gmail.com
 * @since 1.0.0 2024-03-28
 */
@Service
public class InboundServiceImpl extends CrudServiceImpl<InboundDao, InboundEntity, InboundDTO> implements InboundService {

    @Autowired
    private ProductService productService;

    @Autowired
    private InventoryService inventoryService;

    @Override
    public QueryWrapper<InboundEntity> getWrapper(Map<String, Object> params){
        String id = (String)params.get("id");
        String productId = (String)params.get("productId");
        String productTitle = (String)params.get("productTitle");

        QueryWrapper<InboundEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(id), "id", id);
        wrapper.eq(StringUtils.isNotBlank(productId), "product_id", productId);
        if (StringUtils.isNotBlank(productTitle)) {
            List<ProductDTO> productDtoList = productService.getByProTitle(productTitle);
            if (CollectionUtils.isNotEmpty(productDtoList)) {
                List<Long> collect = productDtoList.stream().map(ProductDTO::getId).collect(Collectors.toList());
                wrapper.in("product_id", collect);
            } else {
                return null;
            }
        }

        return wrapper;
    }

    @Override
    public PageData<InboundDTO> inboundPage(Map<String, Object> params) {
        if (getWrapper(params) == null) {
            return new PageData<InboundDTO>(null, 0);
        }
        IPage<InboundEntity> page = baseDao.selectPage(
                getPage(params, null, false),
                getWrapper(params)
        );
        PageData<InboundDTO> pageData = getPageData(page, InboundDTO.class);
        pageData.getList().forEach(e -> {
            ProductDTO productDTO = productService.get(e.getProductId());
            e.setProductTitle(productDTO == null ? "" : productDTO.getTitle());
        });
        return pageData;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void toInventory(InboundDTO dto) {
        InboundEntity inboundEntity = ConvertUtils.sourceToTarget(dto, InboundEntity.class);
        inboundEntity.setStatus(1);
        this.baseDao.updateById(inboundEntity);
        // 加锁
        synchronized (dto.getProductId().toString().intern()) {
            // 入库存
            InventoryDTO inventoryDTO = inventoryService.queryByProId(dto.getProductId());
            if (inventoryDTO == null) {
                InventoryDTO inventoryDto = new InventoryDTO();
                inventoryDto.setProductId(dto.getProductId());
                inventoryDto.setQuantity(dto.getInQuantity());
                inventoryService.save(inventoryDto);
            } else {
                // 原本库存
                Integer oldQuantity = inventoryDTO.getQuantity();
                // 更新库存
                Integer inQuantity = dto.getInQuantity();

                InventoryEntity inventoryEntity = new InventoryEntity();
                inventoryEntity.setId(inventoryDTO.getId());
                inventoryEntity.setQuantity(oldQuantity + inQuantity);
                inventoryService.updateById(inventoryEntity);
            }
        }
    }

    @Override
    public List<InboundDTO> inboundList() {
        // 获取用户信息
        UserDetail user = SecurityUser.getUser();
        // 根据用户查询
        QueryWrapper<InboundEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("creator", user.getId());
        wrapper.orderByDesc("create_date");
        List<InboundEntity> entityList = this.baseDao.selectList(wrapper);
        List<InboundDTO> dtoList = ConvertUtils.sourceToTarget(entityList, InboundDTO.class);
        dtoList.forEach(e -> {
            ProductDTO productDTO = productService.get(e.getProductId());
            e.setProductTitle(productDTO == null ? "" : productDTO.getTitle());
        });
        return dtoList;
    }
}